package com.gome.axwl.aoc.openApi.api.carrierSettle;

import com.anxl.sso.client.api.AccountInfo;
import com.gome.axwl.aoc.common.util.BeanJsonUtil;
import com.gome.axwl.aoc.entity.dto.PageResultDto;
import com.gome.axwl.aoc.entity.dto.carrierSettle.CsApplyInfoDto;
import com.gome.axwl.aoc.entity.enums.BusinessEnum;
import com.gome.axwl.aoc.entity.enums.BusinessEnumDto;
import com.gome.axwl.aoc.entity.po.AmAuditSettingPo;
import com.gome.axwl.aoc.facade.CarrierSettleFacade;
import com.gome.axwl.aoc.facade.SmsSendFacade;
import com.gome.axwl.aoc.service.AuditSettingService;
import com.gome.axwl.aoc.service.feign.MasterDataFeignClient;
import com.gome.commons.core.ErrorCode;
import com.gome.commons.core.ResultData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 项目名称：gome-axwl-aoc-web
 * 类名称：CarrierSettleController
 * 类描述：服务商入驻运营平台
 * @author chenjunjie
 * @since 2018-07-16
 */
@Api(tags = "服务商入驻运营平台微服务")
@RestController
@RequestMapping(value = "/carrierSettle")
public class CarrierSettleController {

    private final static Logger LOGGER = LoggerFactory.getLogger(CarrierSettleController.class);
    @Autowired
    private CarrierSettleFacade carrierSettleFacade;
    @Autowired
    private MasterDataFeignClient masterDataFeignClient;
    @Autowired
    private AuditSettingService auditSettingService;
    @Autowired
    private SmsSendFacade smsSendFacade;
    @Value("${carrierSettle.messageForFinancial}")
    private String messageForFinancial;

    /**
     * 查询申请单草稿
     * @param csPhone
     * @return
     */
    @ApiOperation(value = "查询申请单草稿",notes = "development by yinyuxin")
    @RequestMapping(value = "queryApplyDraft",method = RequestMethod.GET)
    public  ResultData<CsApplyInfoDto> queryApplyDraft(String csPhone){
        return carrierSettleFacade.queryApplyDraft(csPhone);
    }

    /**
     * 根据id查询详情
     * @param applyInfoId
     * @return
     */
    @ApiOperation(value = "查询申请单详情", notes = "development by yinyuxin")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "applyInfoId", value = "单子id", paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "getApprovalDetailById", method = RequestMethod.GET)
    public ResultData<CsApplyInfoDto> getApprovalDetailById(Integer applyInfoId){
        LOGGER.info("接收到微服务请求：查询申请单详情getApprovalDetailById(),param{}",BeanJsonUtil.obj2String(applyInfoId));
        ResultData<CsApplyInfoDto> approvalDetailById = carrierSettleFacade.getApprovalDetailById(applyInfoId);
        LOGGER.info("接收到微服务请求：查询申请单详情getApprovalDetailById(),result{}",BeanJsonUtil.obj2String(approvalDetailById));
        return approvalDetailById;
    }


    /**
     * 新增服务商入驻申请单(保存为草稿，没有启动审批)
     * @param csApplyInfoDto
     * @author yinyuxin@gome.com.cn
     * @return
     */
    @ApiOperation(value = "新增服务商入驻申请单(保存为草稿，没有启动审批)",notes = "development by yinyuxin")
    @RequestMapping(value = "createSettleApplyInfo",method = RequestMethod.POST)
    public  ResultData<Integer> createSettleApplyInfo(@RequestBody CsApplyInfoDto csApplyInfoDto){
        LOGGER.info("接收到微服务请求：新增服务商入驻申请单createSettleApplyInfo(),param{}",BeanJsonUtil.obj2String(csApplyInfoDto));
        ResultData<Integer> settleApplyInfo = carrierSettleFacade.createSettleApplyInfo(csApplyInfoDto);
        LOGGER.info("接收到微服务请求：新增服务商入驻申请单createSettleApplyInfo(),result{}",BeanJsonUtil.obj2String(settleApplyInfo));
        return settleApplyInfo;
    }


    /**
     * 提交服务商入驻申请单（修改+单子状态改为待运营审核）
     * @param csApplyInfoDto
     * @author yinyuxin@gome.com.cn
     * @return
     */
    @ApiOperation(value = "提交服务商入驻申请单（修改+单子状态改为待运营审核）",notes = "development by yinyuxin")
    @RequestMapping(value = "commitSettleApplyInfo",method = RequestMethod.POST)
    public ResultData<Integer> commitSettleApplyInfo(@RequestBody CsApplyInfoDto csApplyInfoDto){
        LOGGER.info("接收到微服务请求：提交服务商入驻申请单commitSettleApplyInfo(),param{}",BeanJsonUtil.obj2String(csApplyInfoDto));
        ResultData<Integer> voidResultData = carrierSettleFacade.commitSettleApplyInfo(csApplyInfoDto);
        LOGGER.info("接收到微服务请求：提交服务商入驻申请单commitSettleApplyInfo(),result{}",BeanJsonUtil.obj2String(voidResultData));
        return voidResultData;
    }

    /**
     * 根据服务商账号查询清单
     * @param csPhone
     * @return
     */
    @ApiOperation(value = "根据服务商账号查询清单",notes = "development by yinyuxin")
    @RequestMapping(value = "queryApplyListByCsphone",method = RequestMethod.GET)
    public  ResultData<PageResultDto<CsApplyInfoDto>> queryApplyListByCsphone(String csPhone, Integer pageNum, Integer pageSize){
        LOGGER.info("接收到微服务请求：根据服务商账号查询清单queryApplyListByCsphone(),param:csPhone{},pageNum{},pageSize{}",csPhone,pageNum,pageSize);
        ResultData<PageResultDto<CsApplyInfoDto>> pageResultDtoResultData = carrierSettleFacade.queryApplyListByCsphone(csPhone, pageNum, pageSize);
        LOGGER.info("接收到微服务请求：根据服务商账号查询清单queryApplyListByCsphone(),result{}",BeanJsonUtil.obj2String(pageResultDtoResultData));
        return pageResultDtoResultData;
    }

    @ApiOperation(value = "校验邀请码是否有效",notes = "development by yinyuxin")
    @RequestMapping(value = "validateInviteNo",method = RequestMethod.GET)
    public ResultData<Boolean> validateInviteNo(String settleInviteNo){
        LOGGER.info("接收到微服务请求：校验邀请码是否有效validateInviteNo(),param:settleInviteNo{}",settleInviteNo);
        List<String> inviteNos=new ArrayList<>();
        inviteNos.add(settleInviteNo);
        ResultData<List<AccountInfo>> accountListByInviteCodes = masterDataFeignClient.getAccountListByInviteCodes(inviteNos);
        if (accountListByInviteCodes==null ||!StringUtils.equals(accountListByInviteCodes.getCode(),ErrorCode.SUCCESS)){
            LOGGER.error("校验邀请码是否有效-->调用主数据接口getAccountListByInviteCodes()出现异常，param{}",BeanJsonUtil.obj2String(inviteNos));
            return new ResultData<>(ErrorCode.FAILOR,ErrorCode.FAILOR_MSG);
        }
        Boolean data=true;
        if (accountListByInviteCodes.getData()==null||accountListByInviteCodes.getData().size()<=0){
            data=false;
        }
        LOGGER.info("接收到微服务请求：校验邀请码是否有效validateInviteNo(),result{}",data);
        return new ResultData<>(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG,data);
    }

    @ApiOperation(value = "提醒财务签署合同",notes = "development by yinyuxin")
    @RequestMapping(value = "remindFinancialSign",method = RequestMethod.GET)
    public ResultData remindFinancialSign(Integer applyInfoId){
        LOGGER.info("接收到微服务请求：提醒财务签署合同remindFinancialSign(),param:applyInfoId{}",applyInfoId);
        //查询财务审批人
        try {
            ResultData resultData=new ResultData();
            AmAuditSettingPo amAuditSettingPo=new AmAuditSettingPo();
            amAuditSettingPo.setDefaultType(1);
            amAuditSettingPo.setStatus((byte)1);
            List<AmAuditSettingPo> amAuditSettingPos = auditSettingService.selectSelective(amAuditSettingPo);
            if (amAuditSettingPos!=null && amAuditSettingPos.size()>0){
                String accountNo=amAuditSettingPos.get(0).getAuditUser();
                //获取用户手机
                ResultData<AccountInfo> userByAccountNo = masterDataFeignClient.getUserByAccountNo(accountNo);
                if (userByAccountNo.getData()!=null){
                    String phone=userByAccountNo.getData().getPhone();
                     resultData=smsSendFacade.sendSmsWithAxwlConfig(phone, messageForFinancial.replace("username", userByAccountNo.getData().getName()));
                    LOGGER.info("接收到微服务请求：提醒财务签署合同remindFinancialSign(),result:applyInfoId{}",BeanJsonUtil.obj2String(resultData));
                    return resultData;
                }
            }
        } catch (Exception e) {
            LOGGER.info("接收到微服务请求：提醒财务签署合同remindFinancialSign(),error:{}",ExceptionUtils.getFullStackTrace(e));
             return new ResultData(ErrorCode.FAILOR,ErrorCode.FAILOR_MSG);
        }
        return new ResultData(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG);
    }

    @ApiOperation(value = "查询数据字典值",notes = "development by yinyuxin")
    @RequestMapping(value = "queryDataDirctionamaryList",method = RequestMethod.GET)
    public ResultData<List<BusinessEnumDto>> queryDataDirctionamaryList(String itemType){
        LOGGER.info("接收到微服务请求：提醒财务签署合同remindFinancialSign(),param:applyInfoId{}",itemType);
        List<BusinessEnumDto> businessEnumDtos = BusinessEnum.businessEnum2List(itemType);
        LOGGER.info("接收到微服务请求：提醒财务签署合同remindFinancialSign(),result:{}",businessEnumDtos);
        return new ResultData<>(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG,businessEnumDtos);
    }
}
